package mylab.base.foundation.orm;

import com.google.common.base.Preconditions;

import javax.sql.DataSource;

import cn.hutool.db.Db;
import lombok.Getter;
import lombok.Setter;
import mylab.base.foundation.lang.Identifiable;
import mylab.base.foundation.orm.ability.Dao;
import mylab.utils.common.ReflectUtil;
import mylab.utils.common.SqlStringUtil;


@Getter
public abstract class BaseDao<T extends Identifiable<Long>> implements Dao<T> {
    protected Class<T> entityClass;
    protected String tableName;
    @Setter
    protected DataSource dataSource;
    protected Db db;

    public BaseDao(DataSource dataSource) {
        this();
        this.dataSource = dataSource;
    }

    public BaseDao() {
        entityClass = ReflectUtil.getGenericType(this.getClass(), 0);
        Preconditions.checkNotNull(entityClass, "泛型参数类型未指定:entityClass");
        tableName = SqlStringUtil.camelToUnderline(entityClass.getSimpleName());
    }

    @Override
    public Db getDb() {
        if (db == null) {
            db = Db.use(getDataSource());
        }

        Preconditions.checkNotNull(db, "db is null");
        return db;
    }
}
